package cj.web.marriage.controllers;

import java.io.File;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.constants.MemuEnum;
import cj.web.login.controllers.BaseController;
import cj.web.marriage.constants.MarriageSCGoodsStatusEnum;
import cj.web.marriage.dao.RefAddressDAO;
import cj.web.marriage.dao.YYBusinessResDAO;
import cj.web.marriage.domain.RefAddress;
import cj.web.marriage.domain.YYBusinessRes;

@Path("/yYBusinessRes")
public class YYBusinessResController extends BaseController{

	private static Logger logger = Logger.getLogger(YYBusinessResController.class.getName());
	
	@Autowired
	private YYBusinessResDAO yYBusinessResDao;
	@Autowired
	private RefAddressDAO refAddressDao;
	
	@Get("show")
	public String show(Model model,YYBusinessRes yYBusinessRes) {
		//MemuEnum
        model.add("MemuEnum",MemuEnum.yYBusinessRes);
        model.add("BusinessStateEnum",EnumSet.allOf(MarriageSCGoodsStatusEnum.class));
        return "/views/marriageYY/yYBusinessResList.vm";
	}

	@Post("getList")
	public String queryList(YYBusinessRes yYBusinessRes) throws ParseException {
		JSONObject jo = new JSONObject();
		List<YYBusinessRes> objs = yYBusinessResDao.query(yYBusinessRes);
		
		for(YYBusinessRes obj:objs){
			obj.setCreateAt(DateUtils.formatDateStr(obj.getCreateAt(), DateUtils.DATE_FULL_STR));
		}
		
		int size = yYBusinessResDao.querySize(yYBusinessRes);
		jo.put("data", objs);
		jo.put("draw", yYBusinessRes.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		//MemuEnum
        model.add("MemuEnum",MemuEnum.yYBusinessRes);
        model.add("BusinessStateEnum",EnumSet.allOf(MarriageSCGoodsStatusEnum.class));
        List<RefAddress> refAddressList = refAddressDao.queryAll();
        model.add("refAddressList",refAddressList);
        return "/views/marriageYY/yYBusinessResDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,YYBusinessRes yYBusinessRes,HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		yYBusinessRes.setState(MarriageSCGoodsStatusEnum.SPSJ.getValue());
		yYBusinessRes.setCreateUser(returnSessionObj(request).getAccount());
		yYBusinessRes.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			yYBusinessResDao.create(yYBusinessRes);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit/{id:[0-9]+}")
	public String edit(Model model,@Param("id") int id)
	{
		model.add("MemuEnum",MemuEnum.yYBusinessRes);
		List<RefAddress> refAddressList = refAddressDao.queryAll();
        model.add("refAddressList",refAddressList);
        
		YYBusinessRes obj = yYBusinessResDao.queryById(id);
		
		if(obj!=null){
			model.add("obj",obj);
			if(obj.getImg() !=null && obj.getImg().length() > 0){
				String[] arr = obj.getImg().split("/");
				if(arr.length == 2){
					model.add("showImg", arr[0] + "/s_" + arr[1]);
				}else{
					model.add("showImg", "");
				}
			}else{
				model.add("showImg", "");
			}
		}
		return "/views/marriageYY/yYBusinessResEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,YYBusinessRes yYBusinessRes,HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		yYBusinessRes.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			yYBusinessResDao.update(yYBusinessRes);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById/{id:[0-9]+}")
	public String deleteById(Model model,@Param("id") int id){
		YYBusinessRes obj = yYBusinessResDao.queryById(id);
		
		if(obj!=null){
			yYBusinessResDao.deleteById(id);
		}
		return "r:../show";
	}
	
	@Get("upById/{id:[0-9]+}")
	public String upById(Model model,@Param("id") int id){
		YYBusinessRes obj = yYBusinessResDao.queryById(id);
		
		if(obj!=null){
			yYBusinessResDao.updateStateById(id,MarriageSCGoodsStatusEnum.SPSJ.getValue());
		}
		return "r:../show";
	}
	
	@Get("downById/{id:[0-9]+}")
	public String downById(Model model,@Param("id") int id){
		YYBusinessRes obj = yYBusinessResDao.queryById(id);
		
		if(obj!=null){
			yYBusinessResDao.updateStateById(id,MarriageSCGoodsStatusEnum.SPXJ.getValue());
		}
		return "r:../show";
	}
	
	@Post("upload")
	public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath_Marriage");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 368, 640, true);//缩率图		640*368
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	@Get("stick/{id:[0-9]+}")//置顶
	public String stick(Model model,@Param("id") int id){
		YYBusinessRes objs = yYBusinessResDao.queryById(id);
		if(objs != null){
			yYBusinessResDao.stick(id);
		}
		
		return "r:../show";
	}
}